package cn.HL.basic.controller;

import cn.HL.basic.exception.BusinessException;
import cn.HL.basic.util.AjaxResult;
import cn.HL.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 分布式文件接口
 * 1.上传接口
 *
 * 2.删除接口
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    //1.文件上传接口
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            String pathTmp = file.getOriginalFilename();
            //获取文件后缀名
            String substring = pathTmp.substring(pathTmp.lastIndexOf(".")+1);
            //上传文件返回一个路径
            String path = FastdfsUtil.upload(file.getBytes(), substring);
            return AjaxResult.me().setResultObj(path);
        } catch (BusinessException e) {//我们自己的业务异常，我们需要自己处理
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }
    //  http://localhost:8080/fastDfs?path=/group1/M00/00/04/CgAIC2Kln6SAEh72AAD1vLo2Ruw09.jpeg
    @DeleteMapping
    public AjaxResult delete(@RequestParam String path){
        try {
           //第一步获取他放在哪里组的 path====>  /group1/M00/00/05/CgAIC2Kl84-Ab0ImAAAAL2vLY64844.jpg
            String substring = path.substring(path.indexOf("/") + 1);
            //   substring==>   group1/M00/00/05/CgAIC2Kl8_mAbXKgAAAAL2vLY64615.jpg
            String sub = substring.substring(0,substring.indexOf("/"));
            //sub ===  >  group1
            //获取后面的文件名   M00/00/05/CgAIC2Kl8_mAbXKgAAAAL2vLY64615.jpg
            String sub2 = substring.substring(substring.indexOf("/") + 1);
            //调用工具类方法直接删除
            FastdfsUtil.delete(sub, sub2);
            return AjaxResult.me();
        } catch (BusinessException e) {//我们自己的业务异常，我们需要自己处理
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除对象失败！"+e.getMessage());
        }
    }



}
